<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>indexOn</title>
    <style>
        code {
            background-color: #535455;
            color:#fff;
            white-space: pre-wrap;
            padding: 15px;
            display: block;
            margin: 10px 0;
            font-size: 15px;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <h1>根据id将数组
        <code>
[
    {
        id: 10,
        name: 'apple'
    },
    {
        id: 20,
        name: 'orange'
    }
]
        </code>
        转成对象，返回:</h1>
    <div id="content"></div>
    <script>
        const indexOn = (arr, key) => arr.reduce((acc, item) => {
            const {
                [key]: id, ...data
            } = item;
            acc[id] = data;
            return acc;
        }, {})
        document.querySelector('#content').innerHTML = JSON.stringify(indexOn([{
                id: 10,
                name: 'apple'
            },
            {
                id: 20,
                name: 'orange'
            }
        ], 'id'))
    </script>
</body>

</html>